package com.moonstar.ws;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.moonstar.pojo.Message;
import com.moonstar.pojo.User;
import com.moonstar.utils.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/chat/{id}")
@Component
public class ChatEndpoint {

    private static StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate){
        ChatEndpoint.stringRedisTemplate=stringRedisTemplate;
    }

    //用来存储每一个客户端对象对应的ChatEndpoint对象
    private static Map<String,Session> onlineUsers = new ConcurrentHashMap<>();


    @OnOpen
    //连接建立时被调用
    public void onOpen(Session session, @PathParam("id") Long id) {
        String s = stringRedisTemplate.opsForValue().get(String.valueOf(id));
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            User user = objectMapper.readValue(s, User.class);
            onlineUsers.put(user.getUsername(),session);
            //将当前在线用户的用户名推送给所有的客户端
            //1,获取消息
            String message = MessageUtils.getMessage(true, null, getNames());
            //2,调用方法进行系统消息的推送
            broadcastAllUsers(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void broadcastAllUsers(String message) {
        for (Session session : onlineUsers.values()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Set<String> getNames() {
        return onlineUsers.keySet();
    }

    @OnMessage
    //接收到客户端发送的数据时被调用
    public void onMessage(String message,Session session,@PathParam("id") Long id) {
        try {
            //将message转换成message对象
            ObjectMapper mapper = new ObjectMapper();
            Message mess = mapper.readValue(message, Message.class);
            //获取要将数据发送给的用户
            String toName = mess.getToName();
            //获取消息数据
            String data = mess.getMessage();
            //获取当前登陆的用户
            String s = stringRedisTemplate.opsForValue().get(String.valueOf(id));
            ObjectMapper objectMapper = new ObjectMapper();
            User user = objectMapper.readValue(s, User.class);
            String fromName = user.getUsername();
            //获取推送给指定用户的消息格式的数据
            String resultMessage = MessageUtils.getMessage(false, fromName, data);
            //发送数据
            onlineUsers.get(toName).getBasicRemote().sendText(resultMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    //连接关闭时被调用
    public void onClose(Session session,@PathParam("id") Long id) {
        try {
            String s = stringRedisTemplate.opsForValue().get(String.valueOf(id));
            ObjectMapper objectMapper = new ObjectMapper();
            User user = objectMapper.readValue(s, User.class);
            String username = user.getUsername();        //从容器中删除指定的用户
            onlineUsers.remove(username);
            //获取推送的消息
            String message = MessageUtils.getMessage(true, null, getNames());
            broadcastAllUsers(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
